package com.ykq.sso.service;

import com.ykq.core.entity.Menu;
import com.ykq.core.entity.User;
import com.ykq.core.vo.R;
import com.ykq.sso.feign.MenuFeign;
import com.ykq.sso.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 闫克起
 * @Description:
 * @Date: Create in 11:23 2024/8/12
 */
@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MenuFeign menuFeign;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1. 根据用户名查询用户信息
        R<User> r = userFeign.getByName(username);
        //2. 判断用户是否存在
        if (r.getCode()==200){
            User user = r.getData();
            //3. 根据用户id查询对应的权限码
            R<List<Menu>> r1 = menuFeign.getByUserId(user.getUserId());
            //获取对应的权限
            List<Menu> menuList = r1.getData();
            Collection<SimpleGrantedAuthority> collection=menuList.stream().map(item->new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
            return new org.springframework.security.core.userdetails.User(username, user.getPassword(), collection);
        }
        return null;
    }
}
